#!/usr/bin/env python
# encoding: utf-8

import sys
import pika
import json
import logging

from lib.utils import ConfigSectionMap

reload(sys)
sys.setdefaultencoding("utf-8")

log = logging.getLogger("")


class JobQueue(object):
    def __init__(self, queue=None):
        self.config = ConfigSectionMap("RABBITMQ")
        self.host = self.config.get("host")
        self.user = self.config.get("username")
        self.password = self.config.get("password")
        self.port = self.config.get("port")
        self.queue = queue
        self.conn = None
        self.chanel = None

    def connection(self):
        u_s = pika.PlainCredentials(self.user, self.password)
        self.conn = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, port=int(self.port), virtual_host=self.queue,
                                                                      credentials=u_s, heartbeat_interval=10,
                                                                      retry_delay=1))
        self.chanel = self.conn.channel()
        self.chanel.queue_declare(queue=self.queue)

    def put(self, data):
        self.chanel.basic_publish(exchange="", routing_key=self.queue, body=json.dumps(data))

    def consumer(self, cb, consumer_tag):
        self.chanel.basic_consume(cb, queue=self.queue, consumer_tag=consumer_tag)
        self.chanel.start_consuming()

    def close(self):
        self.conn.close()
